package com.party.jackclientandroid.okhttp;

import android.util.Log;

import com.party.jackclientandroid.utils.AesCBC;
import com.party.jackclientandroid.utils.MD5Utils;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;
import java.util.TreeMap;

import okhttp3.EncryptFormBody;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * <a href="https://blog.csdn.net/spinchao/article/details/52932145">retrofit/okhttp添加拦截器公共参数签名</a><br>
 * <a href="https://blog.csdn.net/lml0710/article/details/50346701">Android网络请求使用Retrofit+OKHTTP，如何实现参数加密</a><br>
 * 签名拦截器<br>
 */
public class SignInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        try {
            if ("POST".equals(request.method())) {
                return handlerPOST(chain);
            } else {
                return handlerGET(chain);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return chain.proceed(request);
    }

    private Response handlerPOST(Chain chain) throws Exception {
        Request request = chain.request();
        FormBody body = (FormBody) request.body();
        TreeMap<String, String> param_map = new TreeMap<>();
        for (int i = 0; i < body.size(); i++) {
            param_map.put(body.encodedName(i), body.encodedValue(i));
        }
        StringBuilder sign = new StringBuilder();
        Iterator it = param_map.keySet().iterator();
        JSONObject jsonObject = new JSONObject();
        Request.Builder requestBuilder = request.newBuilder();
        while (it.hasNext()) {
            String key = it.next().toString();
            String value = param_map.get(key).toString();
            jsonObject.put(key, value);
            sign.append(key);
            sign.append("=");
            sign.append(value);
            sign.append("&");
        }
        sign = sign.deleteCharAt(sign.length() - 1);
        sign.append("pdkj");
        String jsonStr = jsonObject.toString();
        String aesDecryptStr = AesCBC.encrypt(jsonStr);
        Log.d("SignInterceptor", "aesDecryptStr=====" + aesDecryptStr);

        EncryptFormBody formBody = null;
        if (request.method().equals("POST")) {
            EncryptFormBody.Builder bodyBuilder = new EncryptFormBody.Builder();
            bodyBuilder.addEncoded("key", aesDecryptStr);
            formBody = bodyBuilder.build();
        }

        String signStr = MD5Utils.getMD5Str(sign.toString());
        request = requestBuilder
                .addHeader("sign", signStr)
                .url(request.url())
                .post(formBody)
                .build();
        return chain.proceed(request);

    }

    private Response handlerGET(Chain chain) throws Exception {
        EncryptFormBody formBody = null;
        Request request = chain.request();
        String url = request.url().toString();
        // 获取参数列表
        String[] parts = url.split("\\?");
        if (parts.length < 2) {
            Request.Builder requestBuilder = request.newBuilder();
            request = requestBuilder.build();
            return chain.proceed(request);
        }
        String realUrl = parts[0];
        Request.Builder requestBuilder = request.newBuilder();
        // TreeMap里面的数据会按照key值自动升序排列
        TreeMap<String, String> param_map = new TreeMap<>();
        // 获取参数对
        String[] param_pairs = parts[1].split("&");
        for (String pair : param_pairs) {
            String[] param = pair.split("=");
            // 没有value的参数不进行处理
            if (param.length != 2) {
                continue;
            }
            param_map.put(param[0], param[1]);
        }
        StringBuilder sign = new StringBuilder();
        Iterator it = param_map.keySet().iterator();
        JSONObject jsonObject = new JSONObject();
        while (it.hasNext()) {
            String key = it.next().toString();
            String value = param_map.get(key).toString();
            jsonObject.put(key, value);
            sign.append(key);
            sign.append("=");
            sign.append(value);
            sign.append("&");
        }
        sign = sign.deleteCharAt(sign.length() - 1);
        sign.append("pdkj");
        String jsonStr = jsonObject.toString();
        String aesDecryptStr = AesCBC.encrypt(jsonStr);
        // Md5加密
        String signStr = MD5Utils.getMD5Str(sign.toString());
        Log.d("SignInterceptor", "aesDecryptStr=====" + aesDecryptStr);
        Log.d("SignInterceptor", "realUrl=====" + realUrl);
        // 添加参数
        if (request.method().equals("POST")) {
            EncryptFormBody.Builder bodyBuilder = new EncryptFormBody.Builder();
            bodyBuilder.addEncoded("key", aesDecryptStr);
            formBody = bodyBuilder.build();
        }
        request = requestBuilder
                .addHeader("sign", signStr)
                .url(realUrl)
                .post(formBody)
                .build();
        return chain.proceed(request);
    }
}
